<template>
  <div class="addNodeForm">
    <div class="ef-node-form">
      <div class="ef-node-form-header"></div>
      <div class="ef-node-form-body">

        <el-form :model="node" ref="dataForm" label-width="80px"
                 v-show="type === 'node'" :rules="addFormRules">
          <el-form-item label="类型">
            <el-select clearable v-model="node.nodeType" disabled>
              <el-option v-for="(item, index) in typeList" :key="index"
                         :value="item.type" :label="item.name"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="名称">
            <el-input v-model="node.nodeName"></el-input>
          </el-form-item>

          <el-form-item label="来源" prop="nodeDataId">
            <el-select clearable v-model="node.nodeDataId"
                       @change="selectChanged">

              <el-option v-for="(item, index) in dataList" :key="index"
                         :value="item.id || item.hostid"
                         :label="item.name || item.hostName ">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-button type="danger" icon="el-icon-delete" @click="deleteLine"
                       v-if="node.nodeType != 'room' && node.nodeType != 'sys'">
              删除</el-button>
            <el-button type="primary" icon="el-icon-check" @click="save">保存
            </el-button>
          </el-form-item>

        </el-form>

        <el-form :model="line" ref="dataFormLine" label-width="80px"
                 v-show="type === 'line'">
          <el-form-item label="关系">
            <el-select clearable v-model="line.typeId">
              <el-option v-for="(item, index) in relationList" :key="index"
                         :value="item.id" :label="item.name">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="danger" icon="el-icon-delete" @click="deleteLine">
              删除</el-button>
            <el-button type="primary" icon="el-icon-check" @click="saveLine">保存
            </el-button>
          </el-form-item>
        </el-form>
      </div>
      <!--            <div class="el-node-form-tag"></div>-->
    </div>
  </div>
</template>

<script>
import { cloneDeep } from 'lodash'
import { getAll } from '@/api/assets/dictionaries/relationship' // 关系
import { getNoCiRoom } from '@/api/assets/list/computerRoom' // 机房
import { getAll as getCabinet } from '@/api/assets/list/cabinet'  // 机柜
import { getRoomHosts } from '@/api/assets/list/host'  // 主机
import { deleteRelation, deleteNode } from "@/api/assets/ci/room"  // XX

import { getHostByType } from '@/api/assets/list/host'

import { getList } from '@/api/assets/ci/business' // 获得业务系统
export default {


  // ciId 当前视图ID ,   isAdd 是否是新建的视图
  props: { ciId: Number , isAdd: Boolean}, 

  data () {

    let checkSelectName = (rule, value, callback) => {

      console.log(value);
      // console.log(this.data.nodeList, '----所有节点------'); // 所有 视图节点
      // console.log(this.data, '------已有节点-----');
      if (value == "") {
        callback()
        return
      }
      console.log(JSON.stringify(this.dataList),'---该类型，所有节点--');


      let node = this.data.nodeList.find(el => {
        return el.viewData.id == value
      })
      console.log(JSON.stringify(node))

      console.log(JSON.stringify(this.node)) // 




      if (node) {

      //  if (!this.isNewNode) { // 编辑的时候选中自己，不做验证

        if (node.nodeDataId == 
        this.node.nodeDataId) { // 是自己
          callback()
          return
        }

      // }

        callback(new Error('所选名称已存在'))
      } else {
        callback()
      }



    }

    return {

      visible: true,
      // node 或 line
      type: 'node',
      node: { // 当前编辑的节点
        nodeDataId: ''
      },
      line: {
        relation: {
          name: ''
        }
      },
      data: {},
      datasList: [], // 所有的同类(机房，视图，机柜)节点
      relationList: [],



      addFormRules: {

        nodeDataId: [
          { required: true, message: '请选择名称', trigger: 'blur' },
          { validator: checkSelectName, trigger: 'change' },
        ]

      },

      isNewNode: false, // 是否是新建

    }
  },
  computed: {

    dataList: {
      get () {
        return this.datasList;
      },
      set (val) {
        this.datasList = val
      }
    }
  },
  async created () {

    let ret = await getAll()
    console.log(ret);

    this.relationList = ret.data

    this.saveLine()
  },
  methods: {
    typeList () {
      if (this.data.type == '0') {
        return [
          {
            type: 'room',
            name: '机房'
          },
          {
            type: 'cabinet',
            name: '机柜'
          },
          {
            type: 'host',
            name: '主机'
          }
        ]
      }
      if (this.data.type == '1') {
        return [
          {
            type: 'physical',
            name: '物理机'
          },
          {
            type: 'sys',
            name: '业务系统'
          },
          {
            type: 'virtual',
            name: '虚拟机'
          },
          {
            type: 'database',
            name: '数据库'
          },
          {
            type: 'docker',
            name: 'docker'
          }
        ]
      }
      return [];
    },
    selectChanged () {
      let item = this.dataList.find(ele => {

        if (this.node.nodeDataId == ele.id
          || this.node.nodeDataId == ele.hostid
        ) {
          return true
        }
      })

      if (item) {
        this.node.nodeName = item.name || item.hostName
      }
    },
    // 查找当前业务系统的ID
    findSysId(type){
      let sysNode = this.data.nodeList.find(el=>{
        if (el.nodeType == type) { // 业务系统
          return true
        }
      })

      if(sysNode){
        return sysNode.viewData.id
      }else{
        return ''
      }

    },
    //删除连线
    deleteLine () {

      this.$refs.dataForm.resetFields()

      if ((this.line && this.line.fromCode) || this.node.id) {

        if (this.type === 'node' && this.node.id) {
          deleteNode(this.node.id)
        }
        if (this.type === 'line' && this.line.id) {
          deleteRelation(this.line.id)
        }
      }
      this.$emit('delElement')
    },
    /**
     * 表单修改，这里可以根据传入的ID进行业务信息获取
     * @param data
     * @param id
     */
    async nodeInit (data, id) {
      // 如果没有 nodeDataId ，说明当前是新建的节点

      console.log(data, id)

      this.node.nodeDataId = ''
      this.type = 'node'
      this.data = data
      data.nodeList.filter(node => {
        if (node.code === id) {
          this.node = cloneDeep(node)
        }
      })

      if (this.node.nodeDataId == '' || this.node.nodeDataId == undefined) {
        this.isNewNode = true
      } else {
        this.isNewNode = false
      }
      console.log(this.isNewNode, '----------nodeInit-------');


      if (this.node.nodeType == 'room') {
        const { data } = await getNoCiRoom()
        console.log(data);
        this.dataList = data
      }

      if(this.node.nodeType == 'cabinet'
        || this.node.nodeType == 'host'
      ){

        // 先判断有没有设置机房 
         let roomId = this.findSysId("room")
            console.log(`roomId`, roomId);

        if(roomId=='' || roomId == null){
          // 说明还没有设置机房节点
          this.$message({
            type:'warn',
            message:'请先设置机房节点'
          })
        }else{

          if (this.node.nodeType == 'cabinet') {
            // this.dataList = await getCabinet()
            const { data } = await getCabinet()
            console.log(data);
            this.dataList = data.records;

          }

          if (this.node.nodeType == 'host') {
            const { data } = await getRoomHosts({
              roomId,
              page: {
                current: 1,
                size: 1000
              }
            })
            console.log(data)
            this.dataList = data.records

          }
        }

        
      }


      // case 'physical':
      // case 'sys':
      // case 'virtual':
      // case 'database':
      // case 'docker':

      console.log("=======" + this.node.nodeType);
      if (this.node.nodeType == "sys") { // 业务系统
        let ret = await getList()
        console.log(ret);
        this.dataList = ret.data.records

      }
      //--------业务系统---------
      if (this.node.nodeType == 'physical'
        || this.node.nodeType == 'virtual'
        || this.node.nodeType == 'database'
        || this.node.nodeType == 'docker'
      ) {

        let tt = this.typeList().find(el => { return el.type == this.node.nodeType })

        let sysId = this.findSysId("sys")
        console.log(`sysId`, sysId);

        if(sysId=='' || sysId == null){
          // 说明还没有设置业务系统节点
          this.$message({
            type:'warn',
            message:'请先设置业务系统节点'
          })
        }else{
          // 各类主机
          let ret = await getHostByType({
            // type: 'host',
            type: tt.name,
            ip: '',
            name: '',
            bussId:sysId
          })
          console.log(ret);
          this.dataList = ret.data.records
        } 
      }

      // 新视图，新节点，不处理
      // 新视图，老节点，不处理，
      // 老视图，老节点，要处理，
      // 老视图，没有新节点，
      // 该视图是新建时，不添加。
      console.log(`------------this.isAdd`,this.isAdd );
      console.log(`------------this.isNewNode`,this.isNewNode );
      if(!this.isAdd && !this.isNewNode){
          // 编辑的时候，当节点是 room  或者  sys 时，加入自己
        if ( (this.node.nodeType == 'room' 
           || this.node.nodeType == 'sys')) {
          this.dataList.push({
            id: this.node.nodeDataId,
            name: this.node.nodeName,
          })
        }
      }

      console.log(this.dataList);

    },
    lineInit (line) {
      this.type = 'line'
      this.line = line
      console.log(line)
    },
    // 修改连线
    saveLine () {
      //   console.log("--------111----------");
      //  console.log( this.relationList);
      //  console.log( this.line.typeId);
      this.relationList.forEach(item => {
        if (item.id == this.line.typeId) {
          let json = {
            type: item.id,
            title: item.name
          }
          this.$emit('setLineLabel', this.line.fromCode, this.line.toCode, json)
        }
      })
    },

    save () {

      // console.log(this.node); // 当前编辑的节点
      // console.log(this.dataList); // 所有的同类(机房，视图，机柜)节点
      // console.log(this.data.nodeList[0].viewData.name); // 所有 视图节点

      this.$refs.dataForm.validate(async (valid) => {
        console.log(valid);
        if (!valid) return

        console.log(this.data.nodeList, '----所有节点------'); // 所有 视图节点
        console.log(this.data, '------已有节点-----');


        if (this.node.nodeDataId != '') {
          this.data.nodeList.forEach(node => {

            if (node.code === this.node.code) {

              node.nodeName = this.node.nodeName
              node.nodeDataId = this.node.nodeDataId
              node.left = this.node.left
              node.x = this.node.x
              node.y = this.node.y
              node.top = this.node.top

              this.dataList.forEach(item => {
                if (item.id == this.node.nodeDataId ||
                  item.hostid == this.node.nodeDataId) {

                  // 挂载viewData
                  let dest = {
                    id: item.id || item.hostid,
                    name: item.host || item.name,
                    company: item.company ? item.company.name : '',
                    companyId: item.company ? item.company.id : '',
                    departmentName: item.department ? item.department.name : '',
                    departmentId: item.department ? item.department.id : '',
                    sysUserId: item.sysUser ? item.sysUser.id : '',
                    sysUserName: item.sysUser ? item.sysUser.nickName : '',
                    mobile: item.sysUser ? item.sysUser.mobile : '',
                    email: item.sysUser ? item.sysUser.email : '',

                    // 赋值 available
                    available: item.available ? item.available : 0,

                    // 添加viewType 视图类型
                    viewType: node.nodeType
                  }

                  node.isNewNode = false
                  node.available = item.available ? item.available : 0

                  node.viewData = dest
                  // 机房，机柜，默认为 0 
                  if (node.viewData.available == undefined) {
                    node.viewData.available = 0
                  }
                }
              })
              console.log(node);
              this.$emit('repaintEverything')

            }
          })

          // console.log(this.data.nodeList[0].viewData.name); // 所有 视图节点
        } else {
          this.$message.error('请绑定数据源')
          return
        }

      })
    },


  }
}
</script>

<style>
.el-node-form-tag {
  position: absolute;
  top: 50%;
  margin-left: -15px;
  height: 40px;
  width: 15px;
  background-color: #fbfbfb;
  border: 1px solid rgb(220, 227, 232);
  border-right: none;
  z-index: 0;
}
.addNodeForm {
  position: absolute;
  top: 0;
  right: 0px;
  background: #fff;
  box-shadow: 0px 8px 8px 4px rgba(0, 0, 0, 0.07999999821186066);
  width: 300px;
  padding: 10px 20px;
}
</style>